﻿using CloudFranceTriple.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;

namespace CloudFranceTriple.WebRole.Areas.Member.Controllers
{
    [CloudFranceTriple.WebRole.Filters.InitializeSimpleMembership]
    public class RecruitController : Controller
    {

        private readonly IWebSecurityWrapper _webSecurity;
        public RecruitController()
        {
            this._webSecurity = new WebSecurityWrapper();
        }

        public RecruitController(IWebSecurityWrapper webSecurity)
        {
            this._webSecurity = webSecurity;
        }
        //
        // GET: /Member/Recruit/

        [Authorize(Roles = "RoleFans")]
        public ActionResult Index()
        {
            // View contient l'image "T'es Viré!"
            //    return View();

            var db = new cloudfrAboq2RsDMEntities();

            // Application Serttings
            var recruitCategoryId = Int32.Parse(db.ApplicationSettingSet.SingleOrDefault(ap => ap.Name == "RecruitCategoryId").Value);
            var postTemplate = db.ForumPostSet.Find(Int32.Parse(db.ApplicationSettingSet.SingleOrDefault(ap => ap.Name == "RecruitTemplatePostId").Value));
            var recruitMinimumYes = Int32.Parse(db.ApplicationSettingSet.SingleOrDefault(ap => ap.Name == "RecruitMinimumMemberYes").Value);

            var askToBeFranceTriple = String.Format(CloudFranceTriple.WebRole.Properties.Resources.RecruitTopicLabel, _webSecurity.CurrentUserName);

            var topicset = new ForumTopicSet();
            var forumpostset = new ForumPostSet();
            var pollset = new PollSet();
            var pollAnswers = new List<PollAnswerSet>();
            PollAnswerSet answer;


            // Créer un sujet à partir du modele
            topicset.ForumCategory_Id = recruitCategoryId;
            topicset.AuthorForumTopic = User.Identity.Name;
            topicset.CreationDateForumTopic = System.DateTime.UtcNow;
            topicset.IsUnlocked = true;
            topicset.LabelForumTopic = askToBeFranceTriple;
            topicset.NumberHasBeenSeenForumTopic = 0;
            topicset.OrderForumTopic = 0;
            db.ForumTopicSet.Add(topicset);
            db.SaveChanges();

            // Créer un post à partir du modele
            forumpostset.ForumTopic_Id = topicset.Id;
            forumpostset.PostMessage_Message = postTemplate.PostMessage_Message;
            forumpostset.PostMessage_Author = User.Identity.Name;
            forumpostset.PostMessage_CreationDate = System.DateTime.UtcNow;
            forumpostset.PostMessage_AuthorAdressIp = Request.UserHostAddress.Substring(0, Request.UserHostAddress.Length > 15 ? 15 : Request.UserHostAddress.Length);
            db.ForumPostSet.Add(forumpostset);
            db.SaveChanges();

            // Mettre à jour le compteur de post de l'utilisateur.
            var uc = new CloudFranceTriple.WebRole.Models.UsersContext();
            var userProfile = uc.UserProfiles.Find(_webSecurity.CurrentUserId);
            userProfile.ForumMessagePostedCounter++;
            uc.Entry(userProfile).State = System.Data.EntityState.Modified;
            uc.SaveChanges();

            // Mettre à jour les compteurs de la catégorie:
            var cat = db.ForumCategorySet.Find(db.ForumTopicSet.Find(forumpostset.ForumTopic_Id).ForumCategory_Id);
            cat.LastPostAuthor = forumpostset.PostMessage_Author;
            cat.LastPostCreationDate = forumpostset.PostMessage_CreationDate;
            cat.LastPostId = forumpostset.Id;
            cat.LastPostTopicId = forumpostset.ForumTopic_Id;
            cat.NumberOfMessage++;
            db.Entry(cat).State = System.Data.EntityState.Modified;
            db.SaveChanges();

            // Créer un sondage
            pollset.CreationDatePoll = DateTime.UtcNow.AddDays(30);
            pollset.DescriptionPoll = null;
            pollset.DurationInDays = 7;
            pollset.ForumTopic_Id = forumpostset.ForumTopic_Id;
            pollset.IsMemberOnlyPoll = true;
            pollset.IsPublicPollResult = false;
            pollset.IsRecruitPoll = true;
            pollset.LabelPoll = askToBeFranceTriple;
            pollset.OrderPoll = 0;
            db.PollSet.Add(pollset);
            db.SaveChanges();

            //Créer des réponses
            answer = new PollAnswerSet { LabelPollAnwser = CloudFranceTriple.WebRole.Properties.Resources.RecruitPositivePoll, NumberVotePollAnswer = 0, Poll_Id = pollset.Id };
            db.PollAnswerSet.Add(answer);
            db.SaveChanges();

            // Le candidat vote oui pour lui-même et son vote n'est pas comptabilisé.
            db.PollUserSet.Add(new PollUserSet { PollAnswer_Id = answer.Id, UserId = _webSecurity.CurrentUserId });
            db.SaveChanges();

            answer = new PollAnswerSet { LabelPollAnwser = CloudFranceTriple.WebRole.Properties.Resources.RecruitNegativePoll, NumberVotePollAnswer = 0, Poll_Id = pollset.Id };
            db.PollAnswerSet.Add(answer);
            db.SaveChanges();

            // Rédiriger vers le message en lecture
            return RedirectToAction("Index", "Post", new { id = forumpostset.ForumTopic_Id, area = "Forum" });
        }
    }
}
